// detail.js
const app = getApp();
Page({
  data: {
    currentTab: 'content',
    currentTime: 0,
    duration: 0,
    formattedCurrentTime: '00:00',
    formattedDuration: '00:00',
    muted: false,
    showSpeedMenu: false,
    fullscreen: false,
    playing: false,
    showControls: true,
    hideControlsTimer: null,
    lastTapTime: 0, 
    detail: {} 
  },
  videoContext: null,
  onLoad: function (options) {
    const { id } = options;
    const pages = getCurrentPages();
    const indexPage = pages[pages.length - 2];
    if (indexPage && indexPage.data.MiliTraining) {
      const detail = indexPage.data.MiliTraining.find(item => item.id == id);
      console.log('找到的详情数据:', detail); 
        this.setData({ 
          detail: detail 
        });
    }
    this.videoContext = wx.createVideoContext('myVideo');
    this.startHideControlsTimer();
    
  },
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab
    });
  },playVideo: function () {
    this.videoContext.play();
    this.setData({playing: true});
    this.startHideControlsTimer();
    
},

pauseVideo: function () {
    this.videoContext.pause();
    this.setData({playing: false});
    this.clearHideControlsTimer();
},

videoEnded: function (e) {
    console.log('影片播放结束', e);
    this.setData({
        currentTime: 0,
        formattedCurrentTime: '00:00',
        playing: false,
        showControls: true
    });
    this.videoContext.seek(0);
    this.clearHideControlsTimer();
},

videoTimeUpdate: function (e) {
    const currentTime = e.detail.currentTime;
    const duration = e.detail.duration;
    this.setData({
        currentTime: currentTime,
        duration: duration,
        formattedCurrentTime: this.formatTime(currentTime),
        formattedDuration: this.formatTime(duration)
    });
},

videoFullScreenChange: function (e) {
    console.log('全屏状态改变', e.detail.fullScreen);
    this.setData({fullscreen: e.detail.fullScreen});
},

videoError: function (e) {
    console.error('影片播放错误', e.detail.errMsg);
    wx.showToast({
        title: '影片播放出错，请稍后重试',
        icon: 'none',
        duration: 2000
    });
},

formatTime: function (time) {
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${this.padZero(minutes)}:${this.padZero(seconds)}`;
},

padZero: function (number) {
    return number < 10 ? '0' + number : number;
},

sliderChange: function (e) {
    const value = e.detail.value;
    this.videoContext.seek(value);
    this.setData({
        currentTime: value,
        formattedCurrentTime: this.formatTime(value),
        showControls: true
    });
    this.playVideo();
    this.startHideControlsTimer();
},

sliderChanging: function (e) {
    const value = e.detail.value;
    this.setData({
        formattedCurrentTime: this.formatTime(value),
        showControls: true
    });
    this.clearHideControlsTimer();
},

toggleMute: function () {
    this.setData({
        muted: !this.data.muted,
    });
},

downloadVideo: function () {
    wx.showLoading({
        title: '下载中...',
    })
    wx.downloadFile({
        url: this.data.videoUrl,
        success: function (res) {
            wx.hideLoading();
            if (res.statusCode === 200) {
                wx.saveVideoToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: function () {
                        wx.showToast({
                            title: '视频已保存到相册',
                            icon: 'success',
                            duration: 2000
                        })
                    },
                    fail: function (err) {
                        console.error('保存视频到相册失败', err);
                        wx.showToast({
                            title: '保存视频失败',
                            icon: 'none',
                            duration: 2000
                        })
                    }
                })
            } else {
                console.error('下载文件失败', res);
                wx.showToast({
                    title: '下载文件失败',
                    icon: 'none',
                    duration: 2000
                })
            }
        },
        fail: function (err) {
            wx.hideLoading();
            console.error('下载文件失败', err);
            wx.showToast({
                title: '下载文件失败',
                icon: 'none',
                duration: 2000
            })
        }
    })
},

toggleSpeedMenu: function () {
    this.setData({
        showSpeedMenu: !this.data.showSpeedMenu,
        showControls: true
    });
    this.clearHideControlsTimer();
},

setSpeed: function (speed) {
    this.videoContext.playbackRate(speed);
    this.setData({
        showSpeedMenu: false,
        showControls: true
    });
    this.startHideControlsTimer();
},


setSpeed05: function () {
    this.setSpeed(0.5);
},

setSpeed075: function () {
    this.setSpeed(0.75);
},

setSpeedNormal: function () {
    this.setSpeed(1.0);
},

setSpeed15: function () {
    this.setSpeed(1.5);
},

setSpeed2: function () {
    this.setSpeed(2.0);
},

toggleFullScreen: function () {
    this.setData({
        showControls: true
    });
    if (!this.data.fullscreen) {
        this.videoContext.requestFullScreen();
    } else {
        this.videoContext.exitFullScreen();
    }
    this.startHideControlsTimer();
},
exitFullScreen: function () { // 新增：退出全屏函数
    if (this.data.fullscreen) {
        this.videoContext.exitFullScreen();
    }
},


//  新增播放/暂停控制函数 (点击视频区域中央)
tapVideo: function () {
    const currentTime = Date.now();
    const lastTapTime = this.data.lastTapTime;
    const tapInterval = currentTime - lastTapTime;

    if (!this.data.showControls) { // 控制栏隐藏时
        if (tapInterval < 300) { // 双击暂停 (300ms 内)
            this.pauseVideo();
        } else { // 单击显示控制栏
            this.setData({showControls: true});
            if (this.data.playing) {
                this.startHideControlsTimer(); // 播放时显示控制栏，重新开始计时隐藏
            }
        }
    } else { 
        this.clearHideControlsTimer(); // 清除定时器，防止误触隐藏
        if (tapInterval < 300) { // 双击不处理，避免误操作
            return;
        } else { // 单击暂停播放
            this.pauseVideo();
            this.setData({showControls: true}); // 暂停时保持控制栏显示
        }
    }
    this.setData({lastTapTime: currentTime}); 
},


//  启动定时器，5秒后隐藏控制栏
startHideControlsTimer: function () {
    this.clearHideControlsTimer();
    const timer = setTimeout(() => {
        this.setData({
            showControls: false
        });
    }, 5000);
    this.data.hideControlsTimer = timer;
},

//  清除定时器
clearHideControlsTimer: function () {
    if (this.data.hideControlsTimer) {
        clearTimeout(this.data.hideControlsTimer);
        this.data.hideControlsTimer = null;
    }
},
});